using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using UnityEngine;
using UnityEditor;
using UnityEngine.UIElements;
using UnityEditorInternal;

namespace UnityGameFramework.Editor
{
    public class GameFrameworkSettingsProvider : SettingsProvider
    {
        SerializedObject settingsWrapper;
        UnityEditor.Editor cachedEditor;

        internal static SettingsProvider Instance { get; private set; }

        public GameFrameworkSettingsProvider():base("Project/UnityGameFramework",SettingsScope.Project,new string[] { "Framework" })
        {
        }

        [SettingsProvider]
        public static SettingsProvider CreateSettingsProvider()
        {
            if (Instance == null)
            {
                Instance = new GameFrameworkSettingsProvider();
            }
            return Instance;
        }

        public override void OnGUI(string searchContext)
        {
            if (settingsWrapper == null || settingsWrapper.targetObject == null)
            {
                ScriptableObject settings = (GameFrameworkSettings.SettingObject != null) ? GameFrameworkSettings.SettingObject : LoadOrCreate();
                InitEditorData(settings);
            }

            if (settingsWrapper != null && settingsWrapper.targetObject != null && cachedEditor != null)
            {
                settingsWrapper.Update();
                cachedEditor.OnInspectorGUI();
                settingsWrapper.ApplyModifiedProperties();
            }
        }

        public override void OnActivate(string searchContext, VisualElement rootElement)
        {
            GameFrameworkSettings setting = GameFrameworkSettings.SettingObject;
            if (setting == null)
            {
                setting = LoadOrCreate();
            }
            InitEditorData(setting);
        }

        public override void OnDeactivate()
        {
            cachedEditor = null;
            settingsWrapper = null;
            GameFrameworkSettings.Save();
        }

        private GameFrameworkSettings LoadOrCreate()
        {
            GameFrameworkSettings setting = GameFrameworkSettings.SettingObject;
            if (setting != null) return setting;

            setting = ScriptableObject.CreateInstance<GameFrameworkSettings>();
            GameFrameworkSettings.SettingObject = setting;
            return setting;
        }

        private void InitEditorData(ScriptableObject settings)
        {
            if (!settings) { return; }
            settingsWrapper = new SerializedObject(settings);
            UnityEditor.Editor.CreateCachedEditor(settings, null, ref cachedEditor);
        }
    }
}
